<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import request from '@/utils/sj-request'
import { ElMessage } from 'element-plus'
import KnowledgePointTree from './KnowledgePointTree.vue'
import KnowledgePointForm from './KnowledgePointForm.vue'
import MathFormulaEditor from './MathFormulaEditor.vue'
import { usetikuUserStore } from '@/stores/sj-user'
import { nextTick } from 'vue'
import katex from 'katex'
import 'katex/dist/katex.min.css'

// 定义props
const props = defineProps({
  // 编辑模式时传入的试题数据
  questionData: {
    type: Object,
    default: () => ({})
  },
  // 是否为编辑模式
  isEdit: {
    type: Boolean,
    default: false
  },
  // 学科ID，从学科卡片传入
  subjectId: {
    type: Number,
    default: null
  }
})

// 定义emit事件
const emit = defineEmits(['submit-success', 'cancel'])

// 获取用户信息
const userStore = usetikuUserStore()

// 大题型选择（主观题/客观题）
const questionCategory = ref('objective') // 默认为客观题

// 表单数据
const formData = reactive({
  name: '',
  questionContent: '',
  hardLevel: '中', // 默认中等难度
  answerId: null,
  answerTypeId: null,
  subjectId: null,
  questionTypeId: null,
  knowledgePointId: null,
  userId: userStore.userInfo?.id, // 从用户状态获取
  bigQuestionId: null
})

// 试题内容对话框
const questionContentDialogVisible = ref(false)

// 数学公式编辑器对话框
const mathFormulaDialogVisible = ref(false)
// 当前编辑的选项索引
const currentEditingOptionIndex = ref(-1)

// 试题选项数据
const questionOptions = ref([
  { label: 'A', content: '' },
  { label: 'B', content: '' },
  { label: 'C', content: '' },
  { label: 'D', content: '' }
])

// 添加选项
const addOption = () => {
  questionOptions.value.push({
    label: String.fromCharCode(65 + questionOptions.value.length), // A, B, C...
    content: ''
  })
}

// 移除选项
const removeOption = (index) => {
  questionOptions.value.splice(index, 1)
  // 重新标记选项标签
  questionOptions.value.forEach((option, idx) => {
    option.label = String.fromCharCode(65 + idx)
  })
}

// 打开试题内容对话框
const openQuestionContentDialog = () => {
  // 如果已有试题内容，解析JSON数据填充到选项中
  if (formData.questionContent) {
    try {
      const contentData = JSON.parse(formData.questionContent)
      // 检查是否为新格式（键值对对象）
      if (typeof contentData === 'object' && !Array.isArray(contentData)) {
        // 将对象转换为选项数组
        questionOptions.value = Object.entries(contentData).map(([key, value]) => ({
          label: key,
          content: value
        }))
      } else if (contentData.options && Array.isArray(contentData.options)) {
        // 兼容旧格式
        questionOptions.value = contentData.options
      }
    } catch (e) {
      // 如果解析失败，说明不是JSON格式，将原内容作为第一个选项
      questionOptions.value = [
        { label: 'A', content: formData.questionContent },
        { label: 'B', content: '' },
        { label: 'C', content: '' },
        { label: 'D', content: '' }
      ]
    }
  }
  questionContentDialogVisible.value = true
}

// 保存试题内容
const saveQuestionContent = () => {
  // 验证选项内容不能为空
  const hasEmptyOption = questionOptions.value.some(option => !option.content.trim())
  if (hasEmptyOption) {
    ElMessage.warning('选项内容不能为空')
    return
  }
  
  // 将选项数据转换为指定格式的JSON字符串保存
  const contentObj = {}
  questionOptions.value.forEach(option => {
    contentObj[option.label] = option.content
  })
  formData.questionContent = JSON.stringify(contentObj)
  questionContentDialogVisible.value = false
}

// 标记当前编辑的是标题还是选项
const isEditingTitle = ref(false)

// 打开数学公式编辑器（用于选项）
const openMathFormulaEditor = (optionIndex) => {
  isEditingTitle.value = false
  currentEditingOptionIndex.value = optionIndex
  mathFormulaDialogVisible.value = true
}

// 打开数学公式编辑器（用于标题）
const openTitleFormulaEditor = () => {
  isEditingTitle.value = true
  currentEditingOptionIndex.value = -1
  mathFormulaDialogVisible.value = true
}


// 打开数学公式编辑器（用于主观题内容）
const openSubjectiveContentFormulaEditor = () => {
  isEditingTitle.value = false
  currentEditingOptionIndex.value = -2 // 使用-2表示编辑主观题内容
  mathFormulaDialogVisible.value = true
}

// 处理数学公式确认
const handleFormulaConfirm = (formula) => {
  if (isEditingTitle.value) {
    // 在标题中插入数学公式
    formData.name += `$$${formula}$$`
  } else if (currentEditingOptionIndex.value === -2) {
    // 在主观题内容中插入数学公式
    formData.questionContent += `$$${formula}$$`
  } else if (currentEditingOptionIndex.value >= 0) {
    // 在当前选项内容中插入数学公式
    const option = questionOptions.value[currentEditingOptionIndex.value]
    option.content += `$$${formula}$$`
  }
  mathFormulaDialogVisible.value = false
}

// 渲染数学公式
const renderMathFormula = (content) => {
  if (!content) return content
  
  try {
    // 解析JSON格式的内容
    let parsedContent = content
    try {
      // 检查是否为JSON字符串
      if (typeof content === 'string' && (content.startsWith('{') || content.startsWith('['))) {
        const contentObj = JSON.parse(content)
        if (typeof contentObj === 'object' && !Array.isArray(contentObj)) {
          // 将对象转换为选项数组并水平排列
          parsedContent = Object.entries(contentObj)
            .map(([key, value]) => {
              // 检查选项内容是否包含公式
              if (typeof value === 'string' && value.includes('$$')) {
                // 先处理选项内容中的公式
                const processedValue = value.replace(/\$\$(.*?)\$\$/g, (match, formula) => {
                  try {
                    return katex.renderToString(formula, {
                      throwOnError: false,
                      displayMode: false
                    })
                  } catch (e) {
                    console.error('渲染选项公式出错:', e)
                    return match
                  }
                })
                return `${key}. ${processedValue}`
              }
              return `${key}. ${value}`
            })
            .join('  ')
          return parsedContent
        }
      }
    } catch (e) {
      // 如果解析失败，使用原始内容
      console.log('JSON解析失败，使用原始内容:', e)
      parsedContent = content
    }
    
    // 如果内容不包含公式标记，直接返回
    if (!parsedContent.includes('$$')) return parsedContent
    
    // 替换公式
    const regex = /\$\$(.*?)\$\$/g
    return parsedContent.replace(regex, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          throwOnError: false,
          displayMode: true
        })
      } catch (e) {
        console.error('渲染公式出错:', e)
        return match
      }
    })
  } catch (error) {
    console.error('处理公式内容出错:', error)
    return content
  }
}

// 获取试题内容显示文本
const getQuestionContentText = () => {
  if (!formData.questionContent) return ''
  
  try {
    const contentData = JSON.parse(formData.questionContent)
    // 检查是否为新格式（键值对对象）
    if (typeof contentData === 'object' && !Array.isArray(contentData)) {
      // 将对象转换为选项数组并水平排列，只显示选项内容
      return Object.entries(contentData)
        .map(([key, value]) => `${key}. ${value}`)
        .join('  ')
    }
    // 兼容旧格式
    if (contentData.options && Array.isArray(contentData.options)) {
      return contentData.options.map(option => `${option.label}. ${option.content}`).join('  ')
    }
  } catch (e) {
    // 如果解析失败，返回原内容但不显示JSON字符串
    return ''
  }
  
  return ''
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入试题名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  questionContent: [
    { required: true, message: '请输入试题内容', trigger: 'blur' }
  ],
  hardLevel: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  knowledgePointId: [
    { required: true, message: '请选择所属知识点', trigger: 'change' }
  ],
  subjectId: [
    { required: true, message: '请选择所属学科', trigger: 'change' }
  ],
  subjectId: [
    { required: true, message: '请选择所属学科', trigger: 'change' }
  ],
  bigQuestionId: [
    { required: true, message: '请选择所属大题', trigger: 'change' }
  ],
  answerTypeId: [
    { required: true, message: '请选择答案类型', trigger: 'change' }
  ],
  questionTypeId: [
    { required: true, message: '请选择试题类型', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref(null)
// 答案选择器引用
const answerSelectorRef = ref(null)

// 步骤条
const activeStep = ref(0)

// 过滤后的试题类型列表
const filteredQuestionTypeList = computed(() => {
  if (!questionTypeList.value.length) return []
  
  if (questionCategory.value === 'objective') {
    // 客观题只显示单选题和多选题
    return questionTypeList.value.filter(item => 
      item.name.includes('单选题') || item.name.includes('多选题')
    )
  } else {
    // 主观题过滤掉单选题和多选题
    return questionTypeList.value.filter(item => 
      !item.name.includes('单选题') && !item.name.includes('多选题')
    )
  }
})

// 过滤后的答案类型列表
const filteredAnswerTypeList = computed(() => {
  if (!answerTypeList.value.length) return []
  
  if (questionCategory.value === 'objective') {
    // 客观题只显示客观题答案类型
    return answerTypeList.value.filter(item => item.name.includes('客观题'))
  } else {
    // 主观题显示所有答案类型
    return answerTypeList.value
  }
})

// 学科列表
const subjectList = ref([])

// 试题类型列表
const questionTypeList = ref([])

// 答案类型列表
const answerTypeList = ref([])

// 知识点列表
const knowledgePointList = ref([])
// 知识点树对话框可见性
const knowledgePointTreeVisible = ref(false)
// 选中的知识点名称（用于显示）
const selectedKnowledgePointName = ref('')

// 知识点表单对话框可见性
const knowledgePointFormVisible = ref(false)
// 知识点表单标题
const knowledgePointFormTitle = ref('添加知识点')
// 当前操作的知识点
const currentKnowledgePoint = ref({})

// 大题列表
const bigQuestionList = ref([])

// 难度等级选项
const hardLevelOptions = [
  { value: '易', label: '简单' },
  { value: '中', label: '中等' },
  { value: '难', label: '困难' }
]

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const res = await request({
      url: '/subject/list',
      method: 'get'
    })
    subjectList.value = res.data || []
  } catch (error) {
    console.error('获取学科列表失败:', error)
  }
}

// 获取试题类型列表
const fetchQuestionTypes = async () => {
  try {
    const res = await request({
      url: '/question-type/list',
      method: 'get'
    })
    questionTypeList.value = res.data || []
  } catch (error) {
    console.error('获取试题类型列表失败:', error)
  }
}

// 获取答案类型列表
const fetchAnswerTypes = async () => {
  try {
    const res = await request({
      url: '/answer-type/list',
      method: 'get'
    })
    answerTypeList.value = res.data || []
  } catch (error) {
    console.error('获取答案类型列表失败:', error)
  }
}

// 根据学科ID获取知识点列表
const fetchKnowledgePoints = async (subjectId) => {
  if (!subjectId) {
    knowledgePointList.value = []
    return
  }
  
  try {
    const res = await request({
      url: `/knowledge-point/tree?subjectId=${subjectId}`,
      method: 'get'
    })
    knowledgePointList.value = res.data || []
  } catch (error) {
    console.error('获取知识点列表失败:', error)
  }
}

// 根据学科ID获取大题列表
const fetchBigQuestions = async (subjectId) => {
  if (!subjectId) {
    bigQuestionList.value = []
    return
  }
  
  try {
    const res = await request({
      url: `/big-question/subject/${subjectId}`,
      method: 'get'
    })
    bigQuestionList.value = res.data || []
  } catch (error) {
    console.error('获取大题列表失败:', error)
  }
}

// 处理学科变化
const handleSubjectChange = (subjectId) => {
  formData.knowledgePointId = null
  selectedKnowledgePointName.value = ''
  formData.bigQuestionId = null
  fetchKnowledgePoints(subjectId)
  fetchBigQuestions(subjectId)
}

// 打开知识点树对话框
const openKnowledgePointTree = () => {
  if (!formData.subjectId) {
    ElMessage.warning('请先选择所属学科')
    return
  }
  knowledgePointTreeVisible.value = true
}

// 处理知识点选择
const handleKnowledgePointSelect = (node) => {
  // 如果是新增或编辑知识点
  if (node.isNew || node.isEdit) {
    currentKnowledgePoint.value = node
    knowledgePointFormTitle.value = node.isNew ? '添加知识点' : '编辑知识点'
    knowledgePointFormVisible.value = true
    return
  }
  
  // 正常选择知识点
  formData.knowledgePointId = node.id
  selectedKnowledgePointName.value = node.name
  knowledgePointTreeVisible.value = false
}

// 处理知识点表单提交成功
const handleKnowledgePointFormSuccess = async (data) => {
  knowledgePointFormVisible.value = false
  // 刷新知识点列表
  await fetchKnowledgePoints(formData.subjectId)
  // 如果是新增，自动选中新增的知识点
  if (!currentKnowledgePoint.value.id) {
    ElMessage.success('知识点添加成功，已自动选中')
    // 立即设置知识点ID和名称，不需要延迟
    formData.knowledgePointId = data.id
    selectedKnowledgePointName.value = data.name
    // 关闭知识点树对话框
    knowledgePointTreeVisible.value = false
  } else {
    ElMessage.success('知识点更新成功')
  }
}

// 处理答案类型变化
const handleAnswerTypeChange = () => {
  // 重置答案相关数据
  formData.answerId = null
  
  // 如果是主观题，获取答案库列表
  if (questionCategory.value === 'subjective' && formData.answerTypeId) {
    fetchAnswerList(formData.answerTypeId)
  }
}

// 下一步
const nextStep = async () => {
  if (activeStep.value === 0) {
    // 大题型选择步骤，直接进入基本信息步骤
    activeStep.value = 1
  } else if (activeStep.value === 1) {
    // 验证基本信息表单
    await formRef.value.validate((valid) => {
      if (valid) {
        activeStep.value = 2
      }
    })
  }
}

// 上一步
const prevStep = () => {
  if (activeStep.value === 1 && !props.isEdit) {
    // 只有在非编辑模式下才能回到第一步
    activeStep.value = 0
  } else if (activeStep.value === 2) {
    activeStep.value = 1
  }
}

// 主观题答案相关数据
const useExistingAnswer = ref(false)
const selectedAnswerId = ref(null)
const answerList = ref([])
const subjectiveAnswer = reactive({
  referenceAnswer: '',
  gradingRules: ''
})

// 检查是否有其他选中的选项（用于单选题限制）
const hasOtherSelectedOption = (currentIndex) => {
  return questionOptions.value.some((option, index) => index !== currentIndex && option.isCorrect)
}

// 处理从答案库选择
const handleSelectFromLibrary = (value) => {
  useExistingAnswer.value = value
  if (!value) {
    selectedAnswerId.value = null
  }
}

// 处理选择答案库中的答案
const handleSelectAnswer = (answerId) => {
  selectedAnswerId.value = answerId
  formData.answerId = answerId
}

// 获取答案库列表
const fetchAnswerList = async (typeId) => {
  if (!typeId) return
  
  try {
    // 根据答案类型选择正确的API端点
    const apiUrl = answerTypeList.value.find(item => item.id === typeId)?.name.includes('客观题') 
      ? 'answer/objective/list' 
      : 'answer/subjective/list'
    
    const res = await request({
      url: apiUrl,
      method: 'get',
      params: { answerTypeId: typeId }
    })
    
    answerList.value = res.data || []
  } catch (error) {
    console.error('获取答案列表失败:', error)
  }
}

// 监听答案类型变化，获取对应的答案库列表
watch(() => formData.answerTypeId, (newVal) => {
  if (newVal) {
    fetchAnswerList(newVal)
  }
})

// 提交表单
const submitForm = async () => {
  try {
    let answerId = null
    
    // 检查答案类型是客观题还是主观题
    const isObjectiveAnswer = answerTypeList.value.find(item => item.id === formData.answerTypeId)?.name.includes('客观题')
    
    // 根据答案类型处理答案
    if (isObjectiveAnswer) {
      // 客观题答案处理
      // 只有当大题型为客观题时才验证是否选择了正确答案
      if (questionCategory.value === 'objective') {
        const hasCorrectOption = questionOptions.value.some(option => option.isCorrect)
        if (!hasCorrectOption) {
          ElMessage.warning('请至少选择一个正确答案')
          return
        }
        
        // 获取正确答案的选项字母
        const correctOptions = questionOptions.value
          .filter(option => option.isCorrect)
          .map(option => option.label)
          .join(',')
        
        // 保存客观题答案
        const answerData = {
          answerTypeId: formData.answerTypeId,
          questionAnswer: correctOptions // 只传递选项字母，如 A 或 A,B
        }
        
        const res = await request({
          url: 'answer/objective',
          method: props.isEdit && formData.answerId ? 'put' : 'post',
          data: props.isEdit && formData.answerId ? { ...answerData, id: formData.answerId } : answerData
        })
        
        // 确保从响应中获取答案ID，而不是使用固定值
        answerId = res.data
      } else {
        // 大题型为主观题但答案类型为客观题的情况
        // 检查是否从答案库选择了答案
        if (useExistingAnswer.value && selectedAnswerId.value) {
          // 使用已有答案
          answerId = selectedAnswerId.value
        } else {
          // 如果没有从答案库选择，则验证用户输入
          if (!subjectiveAnswer.referenceAnswer.trim()) {
            ElMessage.warning('答案内容不能为空')
            return
          }
          
          // 保存客观题答案，使用用户输入的答案内容
          const answerData = {
            answerTypeId: formData.answerTypeId,
            questionAnswer: subjectiveAnswer.referenceAnswer // 使用用户输入的答案内容
          }
          
          const res = await request({
            url: 'answer/objective',
            method: props.isEdit && formData.answerId ? 'put' : 'post',
            data: props.isEdit && formData.answerId ? { ...answerData, id: formData.answerId } : answerData
          })
          
          answerId = res.data
        }
      }
    } else {
      // 主观题答案处理
      if (useExistingAnswer.value && selectedAnswerId.value) {
        // 使用已有答案
        answerId = selectedAnswerId.value
      } else if (!useExistingAnswer.value) {
        // 只有当未选择"从答案库选择答案"时才创建新答案
        // 验证主观题答案
        if (!subjectiveAnswer.referenceAnswer.trim()) {
          ElMessage.warning('参考答案不能为空')
          return
        }
        // 保存主观题答案
        const answerData = {
          answerTypeId: formData.answerTypeId,
          referenceAnswer: subjectiveAnswer.referenceAnswer,
          gradingRules: ''
        }
        console.log(answerData)
        
        const res = await request({
          url: 'answer/subjective',
          method: props.isEdit && formData.answerId ? 'put' : 'post',
          data: props.isEdit && formData.answerId ? { ...answerData, id: formData.answerId } : answerData
        })
        
        answerId = res.data
    }
  }
    // 更新试题数据中的答案ID
    // 确保answerId是整数类型
    formData.answerId = answerId ? Number(answerId) : null
    // 提交试题数据
    const questionRes = await request({
      url: '/question',
      method: props.isEdit ? 'put' : 'post',
      data: props.isEdit ? { ...formData, id: props.questionData.id } : formData
    })
    if (questionRes.code === 200) {
      ElMessage.success(props.isEdit ? '试题更新成功' : '试题创建成功')
      emit('submit-success')
    }
    else {
      ElMessage.error(questionRes.message)
    }
  } catch (error) {
    console.error('提交试题失败:', error)
    ElMessage.error('提交失败，请检查表单数据')
  }
}

// 取消操作
const cancelForm = () => {
  emit('cancel')
}

// 初始化编辑模式数据
const initEditData = async () => {
  if (props.isEdit && props.questionData) {
    // 先获取所有必要的数据列表
    await Promise.all([
      fetchSubjects(),
      fetchQuestionTypes(),
      fetchAnswerTypes()
    ])
    
    // 填充表单数据
    Object.keys(formData).forEach(key => {
      if (props.questionData[key] !== undefined) {
        formData[key] = props.questionData[key]
      }
    })
    
    // 加载关联数据
    if (formData.subjectId) {
      await fetchKnowledgePoints(formData.subjectId)
      await fetchBigQuestions(formData.subjectId)
      
      // 如果有知识点ID，获取知识点名称 - 对客观题和主观题都需要
      if (formData.knowledgePointId) {
        // 递归查找知识点
        const findKnowledgePoint = (list, id) => {
          for (const item of list) {
            if (item.id === id) {
              return item
            }
            if (item.children && item.children.length > 0) {
              const found = findKnowledgePoint(item.children, id)
              if (found) return found
            }
          }
          return null
        }
        
        const knowledgePoint = findKnowledgePoint(knowledgePointList.value, formData.knowledgePointId)
        if (knowledgePoint) {
          selectedKnowledgePointName.value = knowledgePoint.name
        }
      }
    }
    
    // 编辑模式下，根据试题类型自动设置大题型
    // 检查试题类型是否为单选题或多选题
    if (formData.questionTypeId) {
      // 确保试题类型列表已加载
      if (questionTypeList.value.length === 0) {
        await fetchQuestionTypes()
      }
      
      const questionType = questionTypeList.value.find(item => item.id === formData.questionTypeId)
      if (questionType) {
        // 如果是单选题或多选题，设置为客观题，否则为主观题
        questionCategory.value = questionType.name.includes('单选题') || questionType.name.includes('多选题') 
          ? 'objective' 
          : 'subjective'
      }
    }
    
    // 如果有试题内容，解析并设置选项
    if (formData.questionContent) {
      if (questionCategory.value === 'objective') {
        try {
          const contentData = JSON.parse(formData.questionContent)
          // 检查是否为新格式（键值对对象）
          if (typeof contentData === 'object' && !Array.isArray(contentData)) {
            // 将对象转换为选项数组
            questionOptions.value = Object.entries(contentData).map(([key, value]) => ({
              label: key,
              content: value,
              isCorrect: false // 默认不是正确答案
            }))
          } else if (contentData.options && Array.isArray(contentData.options)) {
            // 兼容旧格式
            questionOptions.value = contentData.options
          }
        } catch (e) {
          console.error('解析试题内容失败:', e)
        }
      }
      // 主观题内容已在前面通过Object.keys(formData)循环设置到formData.questionContent中
      // 无需特殊处理，因为主观题内容直接显示在文本框中
    }
    
    // 确保试题类型和答案类型在主观题模式下也能正确加载
    if (questionCategory.value === 'subjective') {
      // 确保试题类型已正确设置
      if (formData.questionTypeId && questionTypeList.value.length > 0) {
        const questionType = questionTypeList.value.find(item => item.id === formData.questionTypeId)
        if (!questionType) {
          console.warn('未找到对应的试题类型，ID:', formData.questionTypeId)
        }
      }
      
      // 确保答案类型已正确设置
      if (formData.answerTypeId && answerTypeList.value.length > 0) {
        const answerType = answerTypeList.value.find(item => item.id === formData.answerTypeId)
        if (!answerType) {
          console.warn('未找到对应的答案类型，ID:', formData.answerTypeId)
        }
      }
    }
    
    // 如果有答案ID，获取答案详情并设置正确选项
    if (formData.answerId && formData.answerTypeId) {
      try {
        // 确保答案类型列表已加载
        if (answerTypeList.value.length === 0) {
          await fetchAnswerTypes()
        }
        
        const isObjectiveAnswer = answerTypeList.value.find(item => item.id === formData.answerTypeId)?.name.includes('客观题')
        
        // 获取答案详情
        const res = await request({
          url: isObjectiveAnswer
            ? `answer/objective/${formData.answerId}`
            : `answer/subjective/${formData.answerId}`,
          method: 'get'
        })
        
        if (res.code === 200 && res.data) {
          // 客观题答案处理
          if (isObjectiveAnswer) {
            const correctOptions = res.data.questionAnswer.split(',')
            // 设置正确选项
            questionOptions.value.forEach(option => {
              option.isCorrect = correctOptions.includes(option.label)
            })
          } else {
            // 主观题答案处理
            subjectiveAnswer.referenceAnswer = res.data.referenceAnswer || ''
            subjectiveAnswer.gradingRules = res.data.gradingRules || ''
            // 设置使用已有答案
            useExistingAnswer.value = true
            selectedAnswerId.value = formData.answerId
          }
        }
      } catch (e) {
        console.error('获取答案详情失败:', e)
      }
    }
    
    // 编辑模式下直接跳到第二步（基本信息）
    activeStep.value = 1
  }
}

// 监听大题型变化，重置相关字段
watch(questionCategory, () => {
  // 仅在切换到客观题时重置试题类型和答案类型
  if (questionCategory.value === 'objective') {
    formData.questionTypeId = null
    formData.answerTypeId = null
    formData.answerId = null
  }
  
  // 重置选项的正确答案状态
  questionOptions.value.forEach(option => {
    option.isCorrect = false
  })
  
  // 如果是主观题，不重置试题内容
  if (questionCategory.value === 'subjective') {
    // 保留试题内容
    // 重置主观题答案
    subjectiveAnswer.referenceAnswer = ''
    useExistingAnswer.value = false
    selectedAnswerId.value = null
  }
})

// 组件挂载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchSubjects(),
    fetchQuestionTypes(),
    fetchAnswerTypes()
  ])
  
  // 初始化编辑模式数据
  initEditData()
  
  // 如果传入了学科ID，自动设置学科并获取相关数据
  if (props.subjectId) {
    formData.subjectId = props.subjectId
    handleSubjectChange(props.subjectId)
  }
})
</script>

<style scoped>
.full-width-input {
  width: 100%;
}

.question-form .el-textarea__inner {
  width: 100%;
}
</style>

<template>
  <div class="question-form-container">
    <el-steps :active="activeStep" finish-status="success" simple>
      <el-step v-if="!props.isEdit" title="选择大题型" />
      <el-step title="基本信息" />
      <el-step title="答案设置" />
    </el-steps>
    
    <!-- 步骤一：选择大题型（仅在新建模式显示） -->
    <div v-if="activeStep === 0 && !props.isEdit" class="step-content">
      <div class="question-category-selection">
        <h3>请选择大题型</h3>
        <el-radio-group v-model="questionCategory" size="large">
          <el-radio-button value="objective">客观题</el-radio-button>
          <el-radio-button value="subjective">主观题</el-radio-button>
        </el-radio-group>
        
        <div class="category-description">
          <template v-if="questionCategory === 'objective'">
            <p>客观题：包含单选题和多选题，答案类型将限制为客观题</p>
          </template>
          <template v-else>
            <p>主观题：不包含单选题和多选题，可以直接输入试题内容</p>
          </template>
        </div>
      </div>
      
      <div class="form-actions">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="nextStep">下一步</el-button>
      </div>
    </div>
    
    <!-- 步骤二：基本信息 -->
    <div v-if="activeStep === 1" class="step-content">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="question-form"
      >
        <el-form-item label="试题名称" prop="name">
          <div class="title-input-container">
            <el-input
              v-model="formData.name"
              placeholder="请输入试题名称"
              maxlength="100"
              show-word-limit
            />
            <el-button 
              type="primary" 
              size="small" 
              @click="openTitleFormulaEditor"
              style="margin-left: 8px;"
            >
              公式
            </el-button>
          </div>
          <div v-if="formData.name && formData.name.includes('$$')" class="formula-preview">
            <div class="preview-title">公式预览</div>
            <div class="formula-content" v-html="renderMathFormula(formData.name)"></div>
          </div>
        </el-form-item>
        
        <el-form-item label="试题内容" prop="questionContent">
          <template v-if="questionCategory === 'objective'">
            <div class="question-content-wrapper">
              <div v-if="formData.questionContent">
                <div class="content-preview">
                  <div class="options-display">{{ getQuestionContentText() }}</div>
                  <el-button link @click="openQuestionContentDialog" style="margin-left: 12px;">编辑试题内容</el-button>
                </div>
              </div>
              <div v-else>
                <el-button type="primary" @click="openQuestionContentDialog">编辑试题内容</el-button>
              </div>
            </div>
          </template>
          <!-- 主观题直接使用文本框 -->
          <template v-else>
            <div class="subjective-content-wrapper">
              <el-input
                v-model="formData.questionContent"
                type="textarea"
                :rows="6"
                placeholder="请输入试题内容"
                class="full-width-input"
              />
              <el-button 
                type="primary" 
                size="small" 
                @click="openSubjectiveContentFormulaEditor"
                style="margin-top: 8px;"
              >
                添加公式
              </el-button>
              <div v-if="formData.questionContent && formData.questionContent.includes('$$')" class="formula-preview">
                <div class="preview-title">公式预览</div>
                <div class="formula-content" v-html="renderMathFormula(formData.questionContent)"></div>
              </div>
            </div>
          </template>
        </el-form-item>
        
        <el-form-item label="难度等级" prop="hardLevel">
          <el-select v-model="formData.hardLevel" placeholder="请选择难度等级">
            <el-option
              v-for="item in hardLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属学科" prop="subjectId">
          <el-select
            v-model="formData.subjectId"
            placeholder="请选择所属学科"
            @change="handleSubjectChange"
            :disabled="!!props.subjectId"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="试题类型" prop="questionTypeId">
          <el-select v-model="formData.questionTypeId" placeholder="请选择试题类型">
            <el-option
              v-for="item in filteredQuestionTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="答案类型" prop="answerTypeId">
          <el-select
            v-model="formData.answerTypeId"
            placeholder="请选择答案类型"
            @change="handleAnswerTypeChange"
          >
            <el-option
              v-for="item in filteredAnswerTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="知识点" prop="knowledgePointId">
          <div class="knowledge-point-selector" @click="openKnowledgePointTree">
            <el-input
              v-model="selectedKnowledgePointName"
              placeholder="点击选择知识点"
              readonly
              :disabled="!formData.subjectId"
            >
              <template #suffix>
                <el-icon><ArrowDown /></el-icon>
              </template>
            </el-input>
          </div>
        </el-form-item>
        
        <el-form-item label="所属大题" prop="bigQuestionId">
          <el-select
            v-model="formData.bigQuestionId"
            placeholder="请选择所属大题"
            :disabled="!formData.subjectId"
            clearable
          >
            <el-option
              v-for="item in bigQuestionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <div class="form-actions">
        <el-button v-if="!props.isEdit" @click="prevStep">上一步</el-button>
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="nextStep">下一步</el-button>
      </div>
    </div>
    
    <!-- 步骤三：答案设置 -->
    <div v-else-if="activeStep === 2" class="step-content">
      <!-- 客观题答案设置 -->
      <div v-if="questionCategory === 'objective'" class="objective-answer-selector">
        <h3>请选择正确答案</h3>
        <div class="options-container">
          <div v-for="(option, index) in questionOptions" :key="index" class="option-item">
            <el-checkbox 
              v-model="option.isCorrect" 
              :disabled="formData.questionTypeId && questionTypeList.find(t => t.id === formData.questionTypeId)?.name.includes('单选题') && hasOtherSelectedOption(index)"
            >
              <span class="option-label">{{ option.label }}</span>
              <span class="option-content">{{ option.content }}</span>
            </el-checkbox>
          </div>
        </div>
      </div>
      
      <!-- 主观题答案设置 - 使用答案选择器组件 -->
      <div v-else class="subjective-answer-selector">
        <!-- 答案来源选择 -->
        <div class="answer-source">
          <el-radio-group v-model="useExistingAnswer" @change="handleSelectFromLibrary">
            <el-radio :label="false" :value="false">创建新答案</el-radio>
            <el-radio :label="true" :value="true">从答案库选择</el-radio>
          </el-radio-group>
        </div>
        
        <!-- 从答案库选择 -->
        <div v-if="useExistingAnswer" class="answer-library">
          <el-select
            v-model="selectedAnswerId"
            placeholder="请选择答案"
            style="width: 100%"
            @change="handleSelectAnswer"
          >
            <el-option
              v-for="item in answerList"
              :key="item.id"
              :label="item.id + ' - '+ (answerTypeList && formData.answerTypeId ? answerTypeList.find(t => t.id === formData.answerTypeId)?.name?.includes('客观题') ? item.questionAnswer : item.referenceAnswer : '')"
              :value="item.id"
            />
          </el-select>
        </div>
        
        <!-- 创建新答案 - 简化为单一输入框 -->
        <div v-else class="create-answer">
          <h4>参考答案</h4>
          <el-input
            v-model="subjectiveAnswer.referenceAnswer"
            type="textarea"
            :rows="6"
            placeholder="请输入参考答案"
          />
        </div>
      </div>
      
      <div class="form-actions">
        <el-button @click="prevStep">上一步</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </div>
  
  <!-- 知识点树对话框 -->
  <el-dialog
    v-model="knowledgePointTreeVisible"
    title="选择知识点"
    width="50%"
    :close-on-click-modal="false"
  >
    <KnowledgePointTree
      :subject-id="formData.subjectId"
      @select="handleKnowledgePointSelect"
      @refresh="fetchKnowledgePoints(formData.subjectId)"
    />
  </el-dialog>
  
  <!-- 知识点表单对话框 -->
  <el-dialog
    v-model="knowledgePointFormVisible"
    :title="knowledgePointFormTitle"
    width="40%"
    :close-on-click-modal="false"
  >
    <KnowledgePointForm
      :subject-id="formData.subjectId"
      :knowledge-point="currentKnowledgePoint"
      :is-edit="!!currentKnowledgePoint.id"
      :readonly="userStore.userInfo?.roleName === 'TEACHER'"
      @success="handleKnowledgePointFormSuccess"
      @cancel="knowledgePointFormVisible = false"
    />
  </el-dialog>
  
  <!-- 试题内容对话框 -->
  <el-dialog
    v-model="questionContentDialogVisible"
    title="编辑试题内容"
    width="520px"
    class="question-content-dialog"
    :close-on-click-modal="false"
  >
    <div class="dialog-content-wrapper">
      <div v-for="(option, idx) in questionOptions" :key="option.label" class="option-row">
        <span class="option-label">{{ option.label }}.</span>
        <el-input
          v-model="option.content"
          placeholder="请输入选项内容"
          class="option-input"
          style="width: 400px; font-size: 15px; padding: 6px 12px;"
        />
        <el-button 
          type="primary" 
          size="small" 
          @click="openMathFormulaEditor(idx)"
          style="margin-left: 8px;"
        >
          公式
        </el-button>
        <el-button
          v-if="questionOptions.length > 2"
          icon="Delete"
          type="danger"
          size="small"
          @click="removeOption(idx)"
          style="margin-left: 8px;"
        >删除</el-button>
        <div v-if="option.content.includes('$$')" class="formula-preview">
          <div class="formula-content" v-html="renderMathFormula(option.content)"></div>
        </div>
      </div>
      <el-button type="primary" @click="addOption" style="margin-top: 10px;">添加选项</el-button>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="questionContentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveQuestionContent">保存</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 数学公式编辑器对话框 -->
  <el-dialog
    v-model="mathFormulaDialogVisible"
    title="插入数学公式"
    width="600px"
    :close-on-click-modal="false"
  >
    <MathFormulaEditor @confirm="handleFormulaConfirm" @close="mathFormulaDialogVisible = false" />
  </el-dialog>
</div>
</template>

<style scoped>
  .formula-preview {
    margin-top: 10px;
    padding: 10px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    background-color: #f5f7fa;
  }
  
  .formula-content {
    display: flex;
    justify-content: center;
    padding: 10px;
  }
  
  .preview-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 5px;
  }
.question-form-container {
  padding: 20px;
}

.step-content {
  margin-top: 30px;
}

.question-form {
  max-width: 800px;
}

.title-input-container {
  display: flex;
  align-items: center;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.question-category-selection {
  max-width: 800px;
  margin: 0 auto;
  text-align: center;
}

.question-category-selection h3 {
  margin-bottom: 20px;
  font-weight: 500;
}

.el-radio-group {
  margin-bottom: 20px;
}

.category-description {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  text-align: left;
}

.question-content-wrapper {
  position: relative;
  cursor: pointer;
  width: 100%;
}

.content-preview {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  width: 97%;
}

.options-display {
  margin: 0;
  white-space: normal;
  font-family: inherit;
  line-height: 1.5;
}

.click-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  pointer-events: none;
}

.question-options-container {
  max-width: 100%;
}

.objective-answer,
.subjective-answer {
  max-width: 800px;
}

.option-item {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.option-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-label {
  font-weight: bold;
  margin-right: 15px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  border-radius: 50%;
}

.add-option {
  margin-top: 20px;
}

h3 {
  margin-top: 20px;
  margin-bottom: 15px;
  font-weight: normal;
  color: #606266;
}

/* 答案选择器样式 */
.objective-answer-selector,
.subjective-answer-selector {
  max-width: 800px;
  margin: 0 auto;
}

.options-container {
  margin-top: 20px;
}

.options-container .option-item {
  padding: 10px 15px;
  margin-bottom: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s;
}

.options-container .option-item:hover {
  background-color: #f5f7fa;
}

.options-container .option-label {
  margin-right: 10px;
  font-weight: bold;
}

.options-container .option-content {
  color: #606266;
}

.answer-source {
  margin-bottom: 20px;
}

.subjective-content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
}

.subjective-content-wrapper .el-textarea {
  width: 100%;
}

.question-form .el-form-item {
  max-width: 800px;
  margin: 0 auto 18px;
}

.subjective-content-wrapper .formula-preview {
  margin-top: 10px;
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 10px;
  background-color: #f9f9f9;
}

.answer-library {
  margin-bottom: 20px;
}

.create-answer {
  margin-top: 20px;
}

.create-answer h4 {
  margin-bottom: 10px;
  font-weight: 500;
  color: #606266;
}
.question-content-dialog .el-dialog__body {
  padding: 18px 24px 10px 24px;
  font-size: 15px;
}
.dialog-content-wrapper {
  width: 100%;
  min-width: 400px;
  max-width: 440px;
  margin: 0 auto;
}
.option-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.option-label {
  width: 24px;
  font-weight: 500;
  font-size: 15px;
  color: #333;
}
.option-input {
  flex: 1;
  margin-left: 4px;
}
</style>

